/**
 * Created by admin on 2015/11/30.
 */
app.controller('handlerReceiveOrderCtrl', ['$scope','receiveOrderFactory','appFactory','BaseService','$stateParams','$ionicLoading','$cordovaBarcodeScanner',
    function($scope,receiveOrderFactory,appFactory,BaseService,$stateParams,$ionicLoading,$cordovaBarcodeScanner) {

        $scope.getPackage = function(event,o,index){
            event = event ? event : window.event;
            var obj = event.srcElement ? event.srcElement : event.target;
            obj.disabled=true;
            if(confirm("是否确认包裹已领取？？")===true){
                $scope.rush(o,index);
            }else{
                obj.disabled=false;
                return ;
            }
        }
        $scope.rush = function(o,index){
            //更新订单状态，并且移除调该订单
            $scope.canRush = 0;
            var oid = o.get("orderid");
            var storage = window.localStorage;
            var uid = storage.getItem("uid");
            if (oid){
                var Order = AV.Object.extend("Order");
                var orderQuery = new AV.Query(Order);
                orderQuery.equalTo('orderid',oid);
                orderQuery.first().then(function(res){
                    // 若打包时间比较当前时间超过一小时则不可扫码领取
                    var status = res.get('status');
                    if(status === 4000){
                        BaseService.barscanHandle(uid,oid).then(function(res){
                            //alert(res.msg);
                            alert("领取成功！");
                        }).catch(function(err){
                            //alert(err.msg);
                            alert("出错了！");
                        });
                    }else{
                        BaseService.barscanHandle(uid,oid).then(function(res){
                            //alert(res.msg);
                            alert("领取成功！");
                        }).catch(function(err){
                            //alert(err.msg);
                            alert("没有获取到订单编号！");
                        });
                    }
                }).catch(function(err){
                    alert("没有获取到订单编号！");
                });
            }else{
                alert("没有获取到订单编号！");
            }
        }

        $scope.getOrdersArray = function(mhOid){
            if(mhOid===undefined || mhOid.length<5){
                alert("请输入至少5位连续的订单编号");
                $scope.$broadcast('scroll.refreshComplete');
                return;
            }
            var uid = appFactory.getUserInfo().uid;
            var areaId = appFactory.getUserInfo().user.area;
            var Order = AV.Object.extend("Order");
            async.waterfall([
                function(callback){
                    var orderQuery = new AV.Query(Order);
                    var ORDER_STATUS = [2500,3000,4000];
                    orderQuery.containedIn('status',ORDER_STATUS);
                    //orderQuery.equalTo("syncStatus",0);
                    //orderQuery.notEqualTo('messioned',true);
                    orderQuery.limit(10);
                    //orderQuery.containedIn("areaId",areaId);
                    orderQuery.contains("orderid",mhOid+'');
                    orderQuery.addDescending("bookdate");
                    orderQuery.addDescending("paytime");
                    orderQuery.find().then(function(res){
                        $scope.$apply(function(){
                            //console.log(res)
                            $scope.ordersArray = res;
                            callback(null,$scope.ordersArray);
                        });
                    }).catch(function(err){
                        console.log(err);
                        callback(err);
                    }).finally(function(){
                        $scope.$broadcast('scroll.refreshComplete');
                    });
                },
            ],function(err,result){
                if(err){
                    console.log(err);
                }else{
                    console.log("OK");
                }
            });
        }
        //$scope.getOrdersArray();



        $scope.barscanReceive = function(){
            $cordovaBarcodeScanner
                .scan()
                .then(function(barcodeData) {
                    //alert(JSON.stringify(barcodeData));
                    var cancelled = barcodeData.cancelled;
                    var result = JSON.parse(barcodeData.text);
                    //alert('cancelled:'+cancelled);
                    //alert('result:'+result);
                    if(!cancelled){
                        var oid = result.OID;
                        var storage = window.localStorage;
                        var uid = storage.getItem("uid");
                        if (oid){
                            var Order = AV.Object.extend("Order");
                            var orderQuery = new AV.Query(Order);
                            orderQuery.equalTo('orderid',oid);
                            orderQuery.first().then(function(res){
                                // 若打包时间比较当前时间超过一小时则不可扫码领取
                                var status = res.get('status');
                                if(status === 4000){
                                    var oneday = 1000 * 60 * 60 * 7;
                                    var oneday2 = 1000 * 60 * 60 * 8;
                                    var oneday3 = 1000 * 60 * 60 * 9;
                                    var today = new Date();
                                    today.setHours(0);
                                    today.setMinutes(0);
                                    today.setSeconds(0);
                                    today.setMilliseconds(0);
                                    today = Date.parse(today);

                                    var yesterday = Date.parse(new Date(today - oneday));
                                    var jintiane = Date.parse(new Date(today + oneday2));
                                    var jintiann = Date.parse(new Date(today + oneday3));
                                    var timestamp = Date.parse(new Date());
                                    var warehouseendtime = res.get('warehouseendtime').getTime();

                                    if ((warehouseendtime > yesterday && warehouseendtime < jintiane)&&(timestamp<jintiann)){
                                        BaseService.barscanHandle(uid,oid).then(function(res){
                                            //alert(res.msg);
                                            var r=confirm(res.msg+"\r\n是否继续扫码!");
                                            if (r==true) {
                                                $scope.barscanReceive();
                                            }
                                        }).catch(function(err){
                                            //alert(err.msg);
                                            var r=confirm(res.msg+"\r\n是否继续扫码!");
                                            if (r==true) {
                                                $scope.barscanReceive();
                                            }
                                        });
                                    }else{
                                        //var minute = 1000 * 60;
                                        //var hour = minute * 60;
                                        //var twohour = hour * 2;
                                        //var time = timestamp - warehouseendtime;
                                        //if (time>twohour) {
                                        //    var r = confirm("此订单领取时间已超时,不能扫码!昨日打包完成的订单9点前领取,今日打包完成的订单2小时内领取,\r\n是否继续扫码!");
                                        //    if (r == true) {
                                        //        $scope.barscanReceive();
                                        //    }
                                        //}else{
                                            BaseService.barscanHandle(uid,oid).then(function(res){
                                                //alert(res.msg);
                                                var r=confirm(res.msg+"\r\n是否继续扫码!");
                                                if (r==true) {
                                                    $scope.barscanReceive();
                                                }
                                            }).catch(function(err){
                                                //alert(err.msg);
                                                var r=confirm(res.msg+"\r\n是否继续扫码!");
                                                if (r==true) {
                                                    $scope.barscanReceive();
                                                }
                                            });
                                        //}
                                    }
                                }else{
                                    BaseService.barscanHandle(uid,oid).then(function(res){
                                        //alert(res.msg);
                                        var r=confirm(res.msg+"\r\n是否继续扫码!");
                                        if (r==true) {
                                            $scope.barscanReceive();
                                        }
                                    }).catch(function(err){
                                        //alert(err.msg);
                                        var r=confirm(res.msg+"\r\n是否继续扫码!");
                                        if (r==true) {
                                            $scope.barscanReceive();
                                        }
                                    });
                                }
                            }).catch(function(err){
                                alert(err);
                                var r=confirm("没有扫描到正确的订单信息!\r\n是否继续扫码!");
                                if (r==true) {
                                    $scope.barscanReceive();
                                }
                            });
                        }else{
                            var r=confirm("没有扫描到正确的订单ID信息!\r\n是否继续扫码!");
                            if (r==true) {
                                $scope.barscanReceive();
                            }
                        }
                    }else{
                        alert('扫描异常或退出扫描');
                    }
                }, function(error) {
                    // An error occurred
                });
        }
    }]);


